package ar.com.ford.it.fullEconomics.view.action;

import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.SupplierFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.view.form.SupplierForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class SupplierAction extends AbstractBaseAction {

    /**
     * Setea el mensaje de "busqueda sin resultados" cuando la busqueda no trae
     * resultados
     * 
     * @param request
     * Request donde se guarda el mensaje
     */
    private void searchWithNoResults(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "customMessage", messageResources
                        .getMessage("message.noResults")));
        saveMessages(request, am);
    }

    /**
     * Setea el mensaje de Supplier repetido
     * 
     * @param request
     */
    private void setErrorSupplierAlreadyExists(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);
        am.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage(
                        "customMessage", messageResources
                                .getMessage("supplier.error.repite")));
        this.saveErrors(request, am);
    }    

    private void setErrorDeleted(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);
        am.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage(
                        "customMessage", messageResources
                                .getMessage("supplier.error.deleteExist")));
        this.saveErrors(request, am);
    }
    private void setErrorExistPK(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);
        am.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage(
                        "customMessage", messageResources
                                .getMessage("supplier.error.existSupplierPk")));
        this.saveErrors(request, am);
    }
    
    /**
     * Resetea el formulario y envia a la pagina inicial de Supplier
     * 
     */
    public ActionForward initPage(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        SupplierForm form = (SupplierForm) actionForm;
        SupplierFacade facade = (SupplierFacade) FacadeProvider
        .getFacade(request, SupplierFacade.class);
        form.setClassCode(facade.getComboSupplierType());
        form.setOperation("create");
        request.getSession().setAttribute("classCode",
                facade.getComboSupplierType());
        form.setSuppliers(null);
        return mapping.findForward("success");
    }

    /**
     * Se encarga del manejo de la busqueda de Supplier
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findSupplier(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {                
        ActionMessages am = new ActionMessages();
        SupplierForm form = (SupplierForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession.getUser();
        SupplierFacade facade = (SupplierFacade) FacadeProvider
                .getFacade(request, SupplierFacade.class);
        try {
            Collection<Teess01Supplier> res;
            res = facade.findSupplier(form.getSupplierClassCode(),form.getCodeFind(),form.getDescFind(),user.getTeesg01Plant());
            if (res.isEmpty()) {
                searchWithNoResults(request);
                form.setSuppliers(null);
            }
            request.getSession().setAttribute("suppliers",
                    res);            
            form.SupplierReset();
            form.setSuppliers(res);
            
            form.setOperation("create");
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e.getMessageResource()));
            saveErrors(request, am);
        }        
        return mapping.findForward("success");
    }

    /**
     * Setea los campos de edicion de Supplier con los valores del
     * Economic Source seleccionado mediante el listado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward editSupplier(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        SupplierForm form = (SupplierForm) actionForm;
        form.setEditMapped(form.getNumberSupplier(), "");
        form.setOperation("edit");
        return mapping.findForward("success");
    }

    /**
     * En caso de que se haya seleccionado algun Supplier del listado,
     * entonces lo actualiza, sino llama al metodo encargado de crear el
     * Economic Source
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward createUpdateSupplier(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        ActionMessages am = new ActionMessages();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        SupplierForm form = (SupplierForm) actionForm;
        SupplierFacade facade = (SupplierFacade) FacadeProvider
        .getFacade(request, SupplierFacade.class);
        try {
            if (form.getOperation().equals("create")) {
                if (!facade.supplierNameAlreadyExists(form.getSupplierNameN(), user.getTeesg01Plant())) {
                    Teess01Supplier supplierN = new Teess01Supplier();
                    supplierN.setEess01PlantCodeC(user.getTeesg01Plant());
                    supplierN.setEess01SupplierClassCodeC(form.getSupplierClassN());
                    supplierN.setEess01SupplierCodeC(form.getSupplierCodeN().toUpperCase());
                    supplierN.setEess01SupplierNameN(form.getSupplierNameN().toUpperCase());
                    if(form.getSupplierClassN().equals("F") && form.getSupplierNameN().equals("")){
                        supplierN.setEess01SupplierNameN("GSDB code " + form.getSupplierCodeN());
                    }
                    if(facade.getSupplierByPk(supplierN)==null){
                    facade.createSupplier(supplierN, user);
                    }else{
                        this.setErrorExistPK(request);
                    }
                } else {
                    this.setErrorSupplierAlreadyExists(request);
                }
            } else {
                if (!facade.supplierNameAlreadyExists(form.getSupplierSelected().getEess01SupplierNameN(), user.getTeesg01Plant())) {
                    if(facade.getSupplierByPk(form.getSupplierSelected())!=null){
                        facade.updateSupplier(form.getSupplierSelected(), user);    
                    }else{
                        this.setErrorDeleted(request);
                    }
                    
                }else{
                    this.setErrorSupplierAlreadyExists(request);
                }
            }
            
            form.setOperation("create");
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e.getMessageResource()));
            saveErrors(request, am);
        }
        
        return mapping.findForward("success");
    }

    /**
     * Elimina el Supplier seleccionado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward deleteSupplier(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {

        ActionMessages am = new ActionMessages();
        @SuppressWarnings("unused")
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        SupplierForm form = (SupplierForm) actionForm;
        SupplierFacade facade = (SupplierFacade) FacadeProvider
        .getFacade(request, SupplierFacade.class);
        form.setEditMapped(form.getNumberSupplier(), "");
        try {
                facade.deleteSupplier(form.getSupplierSelected());
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e.getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }
    
    /**
     * Limpia los campos de creacion de Supplier
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward cleanSupplier(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        SupplierForm form = (SupplierForm) actionForm;
        form.SupplierResetPanel();
        form.setOperation("create");
        return mapping.findForward("success");
    }
    
    
    /***************************************************************************
     * Conexion con otras pantallas
     **************************************************************************/
    /**
     * Conexion que permite la conexion hacia la pantalla de Partes y Precio de partes con los
     * datos cargados para realizar la busqueda
     */
    public ActionForward goSupplierByFind(FordActionMapping mapping,
                                        ActionForm actionForm,
                                        HttpServletRequest request,
                                        HttpServletResponse response,
                                        WebSession webSession,
                                        ActionMessages msgs,
                                        ActionMessages warns,
                                        ActionMessages errorMsgs) {
        SupplierForm form = (SupplierForm) actionForm;
        form.setEditMapped(form.getNumberSupplier(), "");
        request.setAttribute("supplierFind", form.getSupplierSelected());
        return mapping.findForward("success");
    }


}
